package nio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class NioServer {
    private static final int PORT = 9999;
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        // 服务端创建 ServerSocketChannel
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        // 绑定端口
        serverSocket.socket().bind(new InetSocketAddress(PORT));
        // 服务端设置为非阻塞
        serverSocket.configureBlocking(false);
        // 将 serverSocket 注册到 Selector 上
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器启动...");
        // 循环处理
        while (true) {
            int count = selector.select();
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        SocketChannel channel = serverSocket.accept();
                        // 将 channel 注册到 selector 中
                        channel.configureBlocking(false);
                        channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                        System.out.println(channel.getRemoteAddress() + " 注册成功");
                    }
                    if (selectionKey.isReadable()) {
                        SocketChannel channel = (SocketChannel)selectionKey.channel();
                        ByteBuffer buffer = (ByteBuffer)selectionKey.attachment();
                        int read = channel.read(buffer);
                        if (read > 0) {
                            System.out.println("读取到数据: " + new String(buffer.array(), 0, read));
                        } else {
                            System.out.println("未读取到数据...");
                        }
                    }
                    // 移除 Key 防止重复处理
                    iterator.remove();
                }
            } else {
                System.out.println("等待事件发生....");
            }
        }
    }
}
